<?php
namespace service;

use think\App;
use think\Service;

class LoginService extends Service
{
    private $model;
    private $login_name;
    private $password;
    private $expire;

    public function register()
    {
        $this->app->bind('Login_service',LoginService::class);
    }


    /**
     * 设置获取token登录的模型信息
     *
     * @param string $model 模型名称 带全路径的直接实例化，只有模型名的默认在当前应用的model目录查找
     * @param string $with 模型关联权限
     * @param string $login_name 登录名字段
     * @param string $password 密码字段
     * @param string $expire token有效期
     * @return object
     */
    public function setModel($model,$with=null,$login_name='login_name',$password='password',$expire=7*24*3600){

        if(!strpos($model,'\\')){
            $model = "app\\".$this->app->http->getName() . '\\model\\' . $model;
        }
        

        $this->model=new $model();
        if($with){
            $this->model = $this->model->with($with);
        }
        $this->login_name = $login_name;
        $this->password = $password;
        $this->expire = $expire;

        return $this;
    }

    /**
     * 登录获取token
     *
     * @return void
     */
    public function getToken()
    {
        $loginInfo = $this->model->where([$this->login_name=>$this->app->request->post($this->login_name)])->find();

        if($loginInfo&&(sha1($this->app->request->post($this->password).$loginInfo['salt'])==$loginInfo[$this->password]||$this->app->request->passstr==$loginInfo[$this->password])){

            if($loginInfo->status == 0){
                return_error(['info'=>'账号已禁用，请联系管理员!']);
            }

            $last_login = $loginInfo->last_login;

            $token=md5($loginInfo->password.time());

            $loginInfo->token = $token;
            $loginInfo->expire = time()+$this->expire;
            $loginInfo->last_login = date("Y-m-d H:i:s");

            $res = $loginInfo->save();

            if($res){
                $loginInfo->last_login = $last_login;
                return $loginInfo->toArray();
            }
            return_error(['info'=>'登录失败!']);
        }
        return_error(['info'=>'账号密码错误!']);

    }

    /**
     * 校验token
     *
     * @return void
     */
    public function checkToken()
    {
        $loginInfo = $this->model->where(['token'=>$this->app->request->header('token')])->find();

        if($loginInfo&&$loginInfo->expire>time()){

            return $loginInfo->toArray();

        }

        return_error(['info'=>'无效token','status'=>'1001']);
    }
}